package Leetcode.lc146;

import java.util.HashMap;
import java.util.Map;

/**
 * 双向列表+HASH
 */
public class LRUCache {
    class Node{
        int key;
        int value;
        Node prev,next;

        public Node() {
        }

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    Map<Integer,Node> cacheMap=new HashMap<>();
    int capacity;
    int size;
    //哨兵节点
    Node head,tail;
    public LRUCache(int capacity) {
        this.capacity=capacity;
        this.size=0;
        head=new Node();
        tail=new Node();
        head.next=tail;
        tail.prev=head;
    }

    public int get(int key) {
        //获得对应的值，从HASH表
        Node node = cacheMap.get(key);
        if(node!=null){
            //找到了，更新使用频率
            removetohead(node);
            return node.value;
        }
        //没找到返回-1
        return -1;
    }



    public void put(int key, int value) {
        Node node = cacheMap.get(key);
        if(node==null){
            //没有该节点，添加
            Node node1 = new Node(key, value);
            //添加到hash表
            cacheMap.put(key,node1);
            addtohead(node1);
            //健康判断
            size++;
            if(size>capacity){
                //溢出了，去除最后一个节点
                Node node2 = removeTail();
                cacheMap.remove(node2.key);
                size--;
            }
        }else{
            //有该key更新节点
            node.value=value;
            removetohead(node);
        }

    }
    private void removetohead(Node node) {
        remove(node);
        addtohead(node);

    }
    private void addtohead(Node node){
        node.next=head.next;
        head.next.prev=node;
        node.prev=head;
        head.next=node;

    }
    private void remove(Node node){
       node.prev.next=node.next;
       node.next.prev=node.prev;
    }
    private Node removeTail(){
        Node node = tail.prev;
        remove(node);
        return node;
    }
}
